let mongoose = require('mongoose'),
    async = require('async'),
    fs = require('fs'),
    appids = mongoose.model('appids'),
    resourcesThumbs = mongoose.model('resources_thumbs'),
    resourcesPost = mongoose.model('resources_posts');

module.exports = (req, res) => {
    let params = req.body,
        status = false, msg = '';

    switch(true){
        case !params.title:
            status = true;
            msg = '标题不能为空！';
            break;
        case !params.content:
            status = true;
            msg = '内容不能为空！';
            break;
        case !params.resourcesType:
            status = true;
            msg = '文章类型不能为空！';
            break;
        case !params.mobile:
            status = true;
            msg = '作者手机号不能为空';
            break;
        case !params.userName:
            status = true;
            msg = '作者用户名不能为空';
            break;
        case params.title.length < 5:
            status = true;
            msg = '标题长度不能少于5个字符';
            break;
        case params.content.length < 20:
            status = true;
            msg = '内容过少';
            break;
        case !params.coverImg:
            status = true;
            msg = '请上传封面图！'
            break;
        default: break;
    }
    // 转换type
    params.resourcesType = params.resourcesType.join(',');

    if(status){
        res.json(resFail(msg));
        return false;
    }

    async.series([
        // 查询pid
        callback => {
            appids.findOne({}, (err, ids) => {
                if(err){
                    res.json(resFail('查询ids出错'))
                }else{
                    this.pid = ids.pid + 1;
                    callback();
                }
            })
        },
        // 更新pid
        callback => {
            appids.update({}, {
                $set: {
                    pid: this.pid
                }
            }, false).exec(err => {
                if(err){
                    res.json(resFail('更新pid出错'))
                }else{
                    callback();
                }
            })
        },
        // 图片数据转换
        callback => {
            let content = params.content,
                contentArr = content.split('"');

            let today = new Date(),
                dirName = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate(),     //目录命名 - 使用当前日期
                dirPath = process.cwd() + '/public/picture/' + dirName;
            dirStatus = fs.existsSync(dirPath); //检测目录是否存在
            // 如果目录不存在，则创建目录
            if(!dirStatus){
                fs.mkdir(dirPath);
            }
            
            // 转换base64为图片，并保存
            contentArr.forEach((e, i) => {
                if(e.indexOf('data:image') > -1){
                    let base64Data = e.replace(/^data:image\/\w+;base64,/, ""),
                        dataBuffer = new Buffer(base64Data, 'base64'),
                        fileName = today.getTime() + '_' + i + '.png',
                        newPath = dirPath + '/' + fileName,
                        outPath = 'http://aimsnode.letp.cn/picture/' + dirName + '/' + fileName;
                        // outPath = 'http://localhost:8032/picture/' + dirName + '/' + fileName;

                    contentArr[i] = outPath;
                    fs.writeFile(newPath, dataBuffer, err => {
                        if(err){
                            res.json(resFail(err))
                        }
                    });
                }
            })

            params.content = contentArr.join('');
            callback();
        },
        // 保存文章数据
        callback => {
            params.pid = this.pid;
            let saveData = new resourcesPost(params);
            saveData.save(err => {
                if(err){
                    res.json(resFail(err));
                }else{
                    callback();
                }
            });
        },
        // 保存点赞数据
        callback => {
            let thumbsData = {
                    pid: this.pid,
                    mobile: params.mobile,
                    userName: params.userName,
                    title: params.title,
                    thumbsCount: 0,
                    thumbsNameList: []
                },
                saveData = new resourcesThumbs(thumbsData);
            
            saveData.save(err => {
                if(err){
                    res.json(resFail(err));
                }else{
                    res.json({
                        result: 1,
                        data: {
                            pid: this.pid
                        }
                    })
                }
            })
        }
    ]);
}